﻿Imports System.Data

Public Class PersistSettingDialog

#Region "ウインドゥイベント"
    Private Sub WindowLoaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        'Setting から設定の復旧
        With My.Settings
            If .UsePersist Then
                txtServerName.Text = .PersistInstance
                txtDatabaseName.Text = .PersistCatalog
                If .PersistUseWindowsAuth Then
                    rdoAuthWindows.IsChecked = True
                Else
                    rdoAuthSQL.IsChecked = True
                    txtAccount.Text = .PersistAccount
                    ptxtPassword.Password = .PersistPassword
                End If
            End If
        End With

    End Sub
#End Region

    Private Sub ExeucteTestConnect(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        Dim conBuilder As New SqlClient.SqlConnectionStringBuilder
        With conBuilder
            .DataSource = txtServerName.Text.Trim
            .InitialCatalog = txtDatabaseName.Text.Trim
            If rdoAuthWindows.IsChecked Then
                .IntegratedSecurity = True
            Else
                .IntegratedSecurity = False
                .UserID = txtAccount.Text.Trim
                .Password = ptxtPassword.Password
            End If
        End With

        Dim connectResult As Boolean = False
        Dim exceptionMessage As String = ""
        Try
            Me.Cursor = Cursors.Wait
            Using sqlConn As New SqlClient.SqlConnection(conBuilder.ToString)
                sqlConn.Open()
                sqlConn.Close()
            End Using
            connectResult = True
        Catch ex As Exception
            exceptionMessage = ex.Message
        Finally
            Me.Cursor = Cursors.Arrow
        End Try
        If connectResult Then
            MessageBox.Show("正常に接続できました。", My.Application.Info.Title,
                            MessageBoxButton.OK, MessageBoxImage.Information)
        Else
            MessageBox.Show(exceptionMessage, My.Application.Info.Title,
                            MessageBoxButton.OK, MessageBoxImage.Warning)
        End If

    End Sub

    Private Sub CommitSettings(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        With My.Settings
            .PersistInstance = txtServerName.Text.Trim
            .PersistCatalog = txtDatabaseName.Text.Trim
            .UsePersist = (rdoAuthWindows.IsChecked)
            If rdoAuthWindows.IsChecked Then
                .UsePersist = True
                .PersistAccount = ""
                .PersistPassword = ""
            Else
                .UsePersist = False
                .PersistAccount = txtAccount.Text.Trim
                .PersistPassword = ptxtPassword.Password
            End If
        End With
        My.Settings.Save()
        Me.Close()
    End Sub

End Class
